<template>
  <div>
    <ul class="aside">
      <li
        v-for="item in letters"
        :key="item"
        :ref="item"
        @click="handleCityClick"
        @touchstart="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd"
      >{{item}}</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'Aside',
  props: {
    cities: Object
  },
  data () {
    return {
      touchStatus: false, // 开关
      timer: null,
      startY: 0
    }
  },
  computed: {// 计算属性
    letters () {
      const letters = []
      for (let i in this.cities) { // 将cities转为数组
        letters.push(i)
      }
      return letters
    }
  },
  updated () {
    this.startY = this.$refs['A'][0].offsetTop
  },
  methods: {
    handleCityClick (e) {
    //  console.log(e.target.innerText)
      this.$emit('change', e.target.innerText)
    },
    handleTouchStart () {
      this.touchStatus = true
    },
    handleTouchMove (e) {
      if (this.touchStatus) {
        // 性能优化 函数截流
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => { // 一次性定时器
          const touchY = e.touches[0].clientY - 87
          const index = Math.floor((touchY - this.startY) / 20)
          // console.log(index)
          // 向父级触发事件
          if (index >= 0 && index < this.letters.length) {
            this.$emit('change', this.letters[index])
          }
        }, 20)
      }
    },
    handleTouchEnd () {
      this.touchStatus = false
    }
  }
}
</script>

<style lang="stylus" scoped>
  .aside{
    width:.2rem;
    position :absolute;
    top:.8rem;
    right:0;
    bottom:0;
    display:flex;
    flex-direction column
    justify-content center
    li{
      text-align center
      line-height .2rem
      color:#00bcd4;
    }
  }
</style>
